package com.kevin.Code.BinarySearch;

/**
 * @author Vinlee Xiao
 * @Classname Sqrtx
 * @Description Leetcode 69. x 的平方根  二分查找 中等难点 注意细节问题越界 二刷
 * @Date 2022/2/26 17:03
 * @Version 1.0
 */
public class Sqrtx {

    /**
     * 注意细节问题: 超过int的最大值
     * 特殊情况是: 1+ 2147483647 == Integer.MIN_VALUE
     *
     * @param x
     * @return
     */
    public int mySqrt(int x) {

        int low = 0;
        int high = x;
        //记录最后的结果值
        int result = 0;

        while (low <= high) {
            int pivot = (low + high) >> 1;


            if ((long) pivot * pivot <= x) {
                result = pivot;
                low = pivot + 1;
            } else {
                high = pivot - 1;
            }

        }

        return result;
    }

    public static void main(String[] args) {
//        Sqrtx sqrtx = new Sqrtx();
//        int i = sqrtx.mySqrt(2147483647);
//        System.out.println(i);


    }
}
